package com.kds.changzhou.handler;

import com.kds.changzhou.message.inbound.SequenceMessage;
import com.kds.changzhou.message.outboud.AbstractOutBoundMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 孔德嵩
 * @date 2023-11-07 13:03
 * @copyright Copyright (c) 2023 Dell
 */
@Slf4j
public class SequenceHandler extends SimpleChannelInboundHandler<SequenceMessage> {

    private HandlerConfig handlerConfig;

    public SequenceHandler(HandlerConfig handlerConfig) {
        this.handlerConfig = handlerConfig;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SequenceMessage msg) throws Exception {

        AbstractOutBoundMessage md5Message = handlerConfig.getOutBoundMessageFactory().buildMD5Message();

        Map data = new HashMap<>();
        data.put("buildingCode", msg.getBuildingCode());
        data.put("gatewayId", msg.getGatewayId());

        String md5 = handlerConfig.getProtocolService().md5Sequence(msg.getSequence());
        data.put("md5", md5);
        md5Message.setData(data);
        ctx.writeAndFlush(md5Message);
    }
}
